package com.rrx.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rrx.model.Administrator;
import com.rrx.model.Menu;
import com.rrx.service.MenuService;
import com.rrx.service.RoleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class MenuController {
    @Resource
    MenuService menuService;
    @Resource
    RoleService roleService;

    @RequestMapping("/addMenu")
    @ResponseBody
    public String addMenu(HttpServletRequest request) {
        String menuName = request.getParameter("menuname");
        String menuParent = request.getParameter("menu_parent");
        String menuRequest = request.getParameter("menu_request");
        String firstPermission = request.getParameter("first_permission");
        String secondPermission = request.getParameter("second_permission");
        String thirdPermission = request.getParameter("third_permission");
        String menuOrder = request.getParameter("menu_order");
        String menuType = request.getParameter("menu_type_check");
        if(menuName == null || menuName.trim() == "")
            return "nameEmpty";
        int order = 0;
        if(menuOrder != null) {
            order = Integer.parseInt(menuOrder);
            if(order < 0)
                return "numberError";
        }
        String permission = "";
        if(firstPermission != null && firstPermission.trim() != "") {
            permission += firstPermission;
            if(secondPermission != null && firstPermission.trim() != "") {
                permission += "."+secondPermission;
                if(thirdPermission != null && thirdPermission.trim() != "") {
                    permission += "."+thirdPermission;
                }
            }else {
                permission += ".*";
            }
        }else {
            if(menuType.equals("2"))
                return "firstPermissionEmpty";
        }
        if(menuRequest == null || menuRequest.trim() == "") {
            return "requestEmpty";
        }
        Integer parentId = null;
        if(menuType.equals("2")) {
            parentId = Integer.parseInt(menuParent);
            if(parentId == -1)
                parentId = null;
        }
        if(!menuService.isMenuExists(menuName)) {
            if(menuService.addMenu(menuName, permission, order, menuRequest, parentId))
                return "success";
        }
        return "fail";
    }

    @RequestMapping("/getAllFirstMenu")
    @ResponseBody
    public String getAllFirstMenu(HttpServletResponse response) {
        Menu[] menus = menuService.getAllFirstMenu();
        if(menus != null && menus.length > 0) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            String json = "[";
            for (Menu m : menus) {
                if (m.getState() == 0)
                    json += "{\"id\":\"" + m.getId() + "\", \"name\":\"" + m.getName() + "\"},";
            }
            json = json.substring(0, json.lastIndexOf(","));
            json += "]";
            return json.toString();
        }
        return "";
    }

    @RequestMapping("/getSecondMenuById")
    @ResponseBody
    public String getSecondMenuById(HttpServletRequest request) {
        String firstMenuId = request.getParameter("id");
        int id = -1;
        try {
            id = Integer.parseInt(firstMenuId);
        }catch(Exception e) {
        }
        if(id >= 0) {
            Menu[] menus = menuService.getSecondMenuById(id);
            if(menus.length > 0) {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    String json = mapper.writeValueAsString(menus);
                    return json;
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    @RequestMapping(value = "/getValidMenuList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getValidMenuList(HttpServletRequest request) {
        Administrator admin = (Administrator) request.getSession().getAttribute("loginAdmin");
        if (admin != null) {
            int id = admin.getId();
            Menu[] firstMenus = menuService.getAllFirstMenu();
            Menu[] secondMenus = menuService.getAdminMenusById(id);
            if (firstMenus != null && firstMenus.length > 0 && secondMenus != null && secondMenus.length > 0) {
                String json = "[";
                for (Menu fm : firstMenus) {
                    json += "{\"firstName\":\"" + fm.getName() + "\",\"secondMenus\":[";
                    boolean b = false;
                    for (Menu sm : secondMenus) {
                        if (sm.getParent() == fm.getId()) {
                            json += "{\"name\":\"" + sm.getName() + "\", \"url\":\"" + sm.getRequest() + "\"},";
                            b = true;
                        }
                    }
                    json = json.substring(0, json.lastIndexOf(","));
                    if(b)
                    json += "]},";
                    else
                        json += "},";
                }
                json = json.substring(0, json.lastIndexOf(","));
                json += "]";
                System.out.println(json);
                return json;
            }
        }
        return "";
    }
}
